home *** CD-ROM | disk | FTP | other *** search
- Path: damon.irf.uni.dortmund.de!broth
- From: rothert@damon.irf.uni-dortmund.de (Bernd Rothert)
- Newsgroups: comp.lang.c++
- Subject: Lifetime of temporary parameter objects
- Date: Wed, 13 Mar 96 09:49:14 GMT
- Organization: Institute of Robotics Research
- Message-ID: <4i6607$l4q@damon.irf.uni-dortmund.de>
- NNTP-Posting-Host: broth.irf
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
-
- I need some advice concerning the lifetime of temporary parameter objects in
- function calls:
-
- It is obviously correct to pass a reference to a temporary object to a
- function - the compiler ensures that the temporary stays alive as long
- as the reference exists (actual parameter of "const Stars&").
-
- What if passing a pointer to the CONTENTS of an explicitly constructed
- temporary:
-
- ---
- #include <string.h>
- #include <iostream.h>
- class Stars {
- public:
- Stars(int n) : _s(new char[n+1]) {
- memset(_s, '*', n);
- _s[n] = '\0';
- }
- ~Stars() {
- delete _s;
- _s = 0;
- }
- const char* get() const { return _s; }
- private:
- char* _s;
- };
- void banner(const Stars& st, const char* s) {
- //=============
- cout << st.get() << endl << s << endl;
- }
- int main() {
- banner(40, Stars(40).get());
- //===============
- return 0;
- }
- ---
-
- The program passes a pointer to the "_s" member of a "Stars" object
- to the "banner" function. This works for every compiler I have seen but I
- don't know if I can rely on this behaviour and prefer defining an auxiliary
- variable which is guaranteed to live until the function call returns.
-
- Can anyone give me a hint?
-
- TIA
- Bernd
-